package com.shadow.baiqun.delegate.receive.goodscheck;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.rey.material.app.DatePickerDialog;
import com.rey.material.app.Dialog;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.ThemeManager;
import com.shadow.baiqun.R;
import com.shadow.baiqun.R2;
import com.shadow.baiqun.config.ItemField;
import com.shadow.baiqun.delegate.PartDataConverter;
import com.shadow.baiqun.delegate.PartDataEntity;
import com.shadow.baiqun.delegate.common.ResultConverter;
import com.shadow.core.delegate.RxShadowDelegate;
import com.shadow.core.net.callback.IError;
import com.shadow.core.net.callback.ISuccess;
import com.shadow.core.net.rx.RxRestClient;
import com.shadow.core.util.toast.ToastUtils;
import com.shadow.ui.recycler.MultipleItemEntity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

public class ModifiDelegate extends RxShadowDelegate {
    private static final String ENTITY = "entity";
    private static final String ORDER_ID = "orderId";

    public static ModifiDelegate create(GoodsCheckEntry entry, int orderId) {
        final ModifiDelegate contentDelegate = new ModifiDelegate();
        final Bundle bundle = new Bundle();
        bundle.putSerializable(ENTITY, entry);
        bundle.putInt(ORDER_ID, orderId);
        contentDelegate.setArguments(bundle);
        return contentDelegate;
    }

    @BindView(R2.id.toolbar)
    Toolbar mToolbar;
    @BindView(R2.id.et_part_name)
    Spinner mSpName;
    @BindView(R2.id.et_part_code)
    EditText mEtPartCode;
    @BindView(R2.id.et_supplier_name)
    EditText mEtSupplierName;
    @BindView(R2.id.et_supplier_code)
    EditText mEtSupplierCode;
    @BindView(R2.id.et_package_number)
    EditText mEtPackageNumber;
    @BindView(R2.id.et_part_number)
    EditText mEtPartNumber;
    @BindView(R2.id.et_remark)
    EditText mEtRemark;
    @BindView(R2.id.et_send_time)
    TextView mTvSendTime;
    @BindView(R2.id.et_clint_name)
    EditText mTvClintName;
    @BindView(R2.id.et_baiqun_group)
    TextView mTvBaiQunGroup;
    @BindView(R2.id.et_status)
    TextView mTvStatus;

    GoodsCheckEntry mEntity;
    private int mOrderId;
    private PartDataEntity mCurrentPart;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mEntity = (GoodsCheckEntry) bundle.getSerializable(ENTITY);
            mOrderId = bundle.getInt(ORDER_ID);
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_part_modifi;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pop();
                }
            });
            mToolbar.setTitle("零件信息修改");
        }
        mEtPartCode.setText(mEntity.getPrepgoodsCCptcode());
        mEtSupplierName.setText(mEntity.getPrepgoodsCSupname());
        mEtSupplierCode.setText(mEntity.getPrepgoodsCSupcode());
        mEtPackageNumber.setText(mEntity.getPrepgoodsCNum());
        mEtPartNumber.setText(mEntity.getPrepgoodsCTotal());
        mEtRemark.setText(mEntity.getPrepgoodsCRemark());
        mTvSendTime.setText(mEntity.getPrepgoodsCSendtime());
        mTvClintName.setText(mEntity.getPrepgoodsCCusbatch());
        mTvBaiQunGroup.setText(mEntity.getPrepgoodsCBatch());
        String status = mEntity.getPrepgoodsCStatus();
        if ("0".equals(status)) {
            status = "未核对";
        } else if ("1".equals(status)) {
            status = "已核对";
        } else {
            status = "修改过";
        }
        mTvStatus.setText(status);
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        requestPartList();
    }

    @OnClick(R2.id.tv_edit)
    public void onCommit() {
        mDisposables.add(RxRestClient.builder()
                .loader(getContext())
                .url("WMS/backstage/collectgoods/addCollectGoodsPartes")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        if (new ResultConverter().isSucceed(response)) {
                            ToastUtils.showToast(getContext(), "修改成功!");
                            pop();
                        } else {
                            ToastUtils.showToast(getContext(), "修改失败!");
                        }
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                })
                .params("prepgoodsCPgid", mOrderId)
                .params("prepgoodsCId", mEntity.getPrepgoodsCId())
                .params("prepgoodsCCompid", mCurrentPart == null ? mEntity.getPrepgoodsCCompid()
                        : mCurrentPart.getId())
                .params("prepgoodsCCptcode", mCurrentPart == null ? mEntity.getPrepgoodsCCptcode()
                        : mCurrentPart.getPartsNum())
                .params("prepgoodsCSupplierid", mCurrentPart == null ? mEntity.getPrepgoodsCSupplierid()
                        : mCurrentPart.getSupportId())
                .params("prepgoodsCSupname", mCurrentPart == null ? mEntity.getPrepgoodsCSupname()
                        : mCurrentPart.getSupportName())
                .params("prepgoodsCSupcode", mCurrentPart == null ? mEntity.getPrepgoodsCSupcode()
                        : mCurrentPart.getSupportNum())
                .params("prepgoodsCNum", mEtPackageNumber.getText().toString())
                .params("prepgoodsCTotal", mEtPartNumber.getText().toString())
                .params("prepgoodsCSendtime", mTvSendTime.getText().toString())
                .params("prepgoodsCCusbatch", mTvClintName.getText().toString())
                .params("prepgoodsCBatch", mTvBaiQunGroup.getText().toString())
                .params("prepgoodsCRemark", mEtRemark.getText().toString())
                .build()
                .unRestPost());
    }

    private void requestPartList() {
        mDisposables.add(RxRestClient.builder()
                .loader(getContext())
                .url("WMS/backstage/collectgoods/getPartes")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        PartDataConverter converter = new PartDataConverter();
                        converter.setJsonData(response);
                        initSpPart(converter.convert());
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                })
                .params("pgid", mOrderId)
                .build()
                .unRestGet());
    }

    private void initSpPart(final List<MultipleItemEntity> locationList) {
        List<String> items = new ArrayList<>();
        if (locationList != null && !locationList.isEmpty()) {
            int mLocation = 0;
            for (int i = 0, size = locationList.size(); i < size; i++) {
                MultipleItemEntity multipleItemEntity = locationList.get(i);
                PartDataEntity entity = multipleItemEntity.getField(ItemField.ITEM_OBJ);
                items.add(entity.getPartsName());
                if (entity.getId() == mEntity.getPrepgoodsCCompid()) {
                    mCurrentPart = entity;
                    mLocation = i;
                }
            }
            ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), R.layout.row_spn, items);
            adapter.setDropDownViewResource(R.layout.row_spn_dropdown);
            mSpName.setAdapter(adapter);
            mSpName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                    MultipleItemEntity multipleItemEntity = locationList.get(position);
                    PartDataEntity entity = multipleItemEntity.getField(ItemField.ITEM_OBJ);
                    mCurrentPart = entity;
                    mEtPartCode.setText(entity.getPartsNum());
                    mEtSupplierName.setText(entity.getSupportName());
                    mEtSupplierCode.setText(entity.getSupportNum());
                }

                @Override
                public void onNothingSelected(AdapterView<?> adapterView) {

                }
            });
            mSpName.setSelection(mLocation);
        }
    }

//    @OnClick(R2.id.et_clint_name)
//    public void onChangeClintName() {
//        Dialog.Builder builder;
//        boolean isLightTheme = ThemeManager.getInstance().getCurrentTheme() == 0;
//        builder = new DatePickerDialog.Builder(isLightTheme ? R.style.Material_App_Dialog_DatePicker_Light : R.style.Material_App_Dialog_DatePicker) {
//            @Override
//            public void onPositiveActionClicked(DialogFragment fragment) {
//                DatePickerDialog dialog = (DatePickerDialog) fragment.getDialog();
//                String date = dialog.getFormattedDate(new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA));
//                mTvClintName.setText(date);
//                super.onPositiveActionClicked(fragment);
//            }
//
//            @Override
//            public void onNegativeActionClicked(DialogFragment fragment) {
//                super.onNegativeActionClicked(fragment);
//            }
//        };
//        builder.positiveAction("确定")
//                .negativeAction("取消")
//        ;
//        DialogFragment fragment = DialogFragment.newInstance(builder);
//        fragment.show(getFragmentManager(), null);
//    }

    @OnClick(R2.id.et_send_time)
    public void onChangeSendTime() {
        Dialog.Builder builder;
        boolean isLightTheme = ThemeManager.getInstance().getCurrentTheme() == 0;
        builder = new DatePickerDialog.Builder(isLightTheme ? R.style.Material_App_Dialog_DatePicker_Light : R.style.Material_App_Dialog_DatePicker) {
            @Override
            public void onPositiveActionClicked(DialogFragment fragment) {
                DatePickerDialog dialog = (DatePickerDialog) fragment.getDialog();
                String date = dialog.getFormattedDate(new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA));
                mTvSendTime.setText(date);
                super.onPositiveActionClicked(fragment);
            }

            @Override
            public void onNegativeActionClicked(DialogFragment fragment) {
                super.onNegativeActionClicked(fragment);
            }
        };
        builder.positiveAction("确定")
                .negativeAction("取消")
        ;
        DialogFragment fragment = DialogFragment.newInstance(builder);
        fragment.show(getFragmentManager(), null);
    }

    @OnClick(R2.id.et_baiqun_group)
    public void onChangeGroup() {
        Dialog.Builder builder;
        boolean isLightTheme = ThemeManager.getInstance().getCurrentTheme() == 0;
        builder = new DatePickerDialog.Builder(isLightTheme ? R.style.Material_App_Dialog_DatePicker_Light : R.style.Material_App_Dialog_DatePicker) {
            @Override
            public void onPositiveActionClicked(DialogFragment fragment) {
                DatePickerDialog dialog = (DatePickerDialog) fragment.getDialog();
                String date = dialog.getFormattedDate(new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA));
                mTvBaiQunGroup.setText(date);
                super.onPositiveActionClicked(fragment);
            }

            @Override
            public void onNegativeActionClicked(DialogFragment fragment) {
                super.onNegativeActionClicked(fragment);
            }
        };
        builder.positiveAction("确定")
                .negativeAction("取消")
        ;
        DialogFragment fragment = DialogFragment.newInstance(builder);
        fragment.show(getFragmentManager(), null);
    }
}
